<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h2 class="name"></h2>
  <script>
    const obj = {
      name: "why",
      age: 18,
      height: 1.88
    }
    // 需求:监听对象属性的所有操作
    // 监听属性操作
    // 1.针对一个属性
    // let _name = obj.name
    // Object.defineProperty(obj,'name',{
    //   set:function(newValue){
    //     console.log("给name设置了新的值:"+newValue)
    //     _name = newValue
    //   },
    //   get:function(){
    //     console.log("监听:获取name的值")
    //     return _name
    //   }
    // })

    // 2.监听所有属性
    const keys = Object.keys(obj)
    for (const key of keys) {
      let value = obj[key]
      Object.defineProperty(obj, key, {
        set: function(newValue) {
          console.log(`监听: 给${key}设置了新的值:`, newValue)
          value = newValue
        },
        get: function() {
          console.log(`监听: 获取${key}的值`)
          return value
        }
      })
    }

    console.log(obj.name)
    obj.name = 'kobe'
    console.log(obj.age)
    obj.age = 17

    // 什么是响应式
    const nameEl = document.querySelector('.name')
    nameEl.innerHTML = obj.name
    obj.name = 'james'
    // nameEl.innerHTML = obj.name


  </script>
</body>

</html>